/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Properties;
import tal.drivechain.parsing.ParsingAid;
import tal.drivechain.plugin.ModulePackageManager;

/**
 *
 * @author eisental
 */
public class ConfigManager {
    static final String PREFS_PATH = System.getProperty("user.dir") + "/prefs";
    static final String PACKS_PATH = System.getProperty("user.dir") + "/packs";
    static final String PACKLIBS_PATH = System.getProperty("user.dir") + "/packlibs";
    private String logger;
    private String defaultPackage;
    private String scriptPath;
    private Properties prefs;
    private PrintStream out;

    public ConfigManager(OutputStream o) {
        this.out = new PrintStream(o);
        //read properties from the preferences file.
        out.println("- prefrences: " + ParsingAid.makeDots(PREFS_PATH, "- prefrences: ".length()));
        prefs = new Properties();
        try {
            prefs.load(new FileInputStream(new File(PREFS_PATH)));
        } catch (IOException ex) {
            out.println("Error while reading preferences:\n\t" + ex.getMessage());
        }

        //set the default modules package
        defaultPackage = prefs.getProperty("dc.defaultPackage");
        if (defaultPackage==null)
            out.println("Warning: dc.defaultPackage preferences was not found.");
        else {
            out.println("- default modules package: " + ParsingAid.makeDots(defaultPackage, "- default modules package: ".length()));
        }

        //set the default logger
        logger = prefs.getProperty("dc.defaultLogger");
        if (logger==null)
            out.println("Warning: dc.defaultLogger preferences property was not found.");
        else {
            out.println("- default logger: " + ParsingAid.makeDots(logger, "- default logger: ".length()));
        }

        //set the path to look for drivechain scripts.
        scriptPath = prefs.getProperty("dc.scriptPath");
        if (scriptPath==null) 
            out.println("Warning: dc.scriptPath preferences property was not found.");
        else {
            if (scriptPath.charAt(scriptPath.length()-1)!='/' &&
                    scriptPath.charAt(scriptPath.length()-1)!='\\')
                scriptPath += "\\";
            out.println("- scripts path: " + ParsingAid.makeDots(scriptPath, "- scripts path: ".length()));
        }

        out.println("- module packages path: " + ParsingAid.makeDots(PACKS_PATH, "- module packages path: ".length()));
    }

    public String getDefaultLogger() { return logger; }
    public String getDefaultPackage() { return defaultPackage; }
    public String getScriptsPath() { return scriptPath; }

    public void loadPackages() throws IllegalArgumentException {
        File dir = new File(PACKS_PATH);
        if (!dir.exists() || !dir.isDirectory())
            throw new IllegalArgumentException("Can't find packages folder: " + PACKS_PATH);

        boolean added = true;

        out.println("- loading packages: ");
        boolean first = true;
        for (File file : dir.listFiles()) {
            try {
                ModulePackageManager m = PluginLoader.loadPackage(file.getAbsolutePath());
                out.println("  * " + m.getPackageConfiguration().getPackageInfo().getVersion().toString(true, true, true, true) +
                        " (" + file.getName() + ").");
            } catch (Exception e) { added = false; }
        }
        PluginLoader.checkPackageDependencies();
    }

    public void addClassPath() {
        File dir = new File(PACKLIBS_PATH);
        try {
            PluginLoader.addLibraryPath(PACKLIBS_PATH);
            out.println("- package libraries path: " + ParsingAid.makeDots(PACKLIBS_PATH, "- package libraries path: ".length()));
        } catch (IOException ex) {
            out.println("Can't add " + PACKLIBS_PATH + " to java library path. " + ex.getMessage()); System.exit(-1); 
        }
        if (!dir.exists() || !dir.isDirectory())
            throw new IllegalArgumentException("Can't find package libs folder: " + PACKLIBS_PATH);

        out.print("\n- adding libraries:");
        for (File path : dir.listFiles()) {
            try {
                PluginLoader.addClassPath(path.getAbsolutePath());
                out.print(" * " + path.getName());
            } catch (IOException ie) { out.println("Can't add " + path.getAbsolutePath() + " to classpath. " + ie.getMessage()); System.exit(-1); }
        }
        out.println("\n");
    }

    public void setConfigDefaults() {
        if (defaultPackage!=null)
            PluginLoader.setDefaultPackage(defaultPackage);
        if (scriptPath!=null)
            Globals.setScriptsPath(scriptPath);
    }
}